package com.blog.controller;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

        String methodStr = req.getParameter("method");
//        if (methodStr == null || methodStr.trim().isEmpty()) {
//            methodStr = "index";
//        }
        if (StrUtil.isBlank(methodStr)) {
            methodStr = "index";
        }
        if (methodStr == null || methodStr.trim().isEmpty()) {
            methodStr = req.getParameter("action");
        }


        try {
//            Class<?> clazz = this.getClass();
//            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
//            Object result = method.invoke(this, req, resp);

            Object result = ReflectUtil.invoke(this, methodStr, req, resp);

            if (result != null) {
                String resultStr = (String) result;
                if (resultStr.startsWith("forward:")) {
                    String path = resultStr.substring("forward:".length());
                    req.getRequestDispatcher(path).forward(req, resp);
                } else {
                    resp.sendRedirect(resultStr);
                }
            }
        } catch (Exception e) {
            throw new ServletException("BaseServlet 方法调用失败", e);
        }
    }

    public static void main(String[] args) {
//        HttpRequest request = new HttpRequest("http://localhost:8086/BlogManagement_war/articleServlet?method=Start&id=4");
//        request.header("cookie", "JSESSIONID=DD69022BB9C195891D1D289B2056310D");
//        HttpResponse execute = request.execute();
//
//        System.out.println(execute.body());

        String json = HttpUtil.get("https://api.mairuiapi.com/hslt/list/LICENCE-66D8-9F96-0C7F0FBCD073");
        System.out.println( json);

        List<Share> list = JSONUtil.toList(json, Share.class);
        System.out.println( list);
    }
}

class Share {
    private String dm;
    private String mc;
    private String jys;

    public String getDm() {
        return dm;
    }

    public void setDm(String dm) {
        this.dm = dm;
    }

    public String getMc() {
        return mc;
    }

    public void setMc(String mc) {
        this.mc = mc;
    }

    public String getJys() {
        return jys;
    }

    public void setJys(String jys) {
        this.jys = jys;
    }
}